package com.xiaoding.serialhelper;

import android.animation.ObjectAnimator;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.NavUtils;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.content.Intent;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.github.clans.fab.FloatingActionMenu;
import com.xiaoding.data.Data_sync;
import com.xiaoding.tcp.TCP_client;
import com.xiaoding.tcp.TCP_service;
import com.xiaoding.udp.UdpClient;
import com.xiaoding.udp.UdpHelper;
import com.xiaoding.udp.UdpServer;

import edu.swu.pulltorefreshswipemenulistview.library.PullToRefreshSwipeMenuListView;
import edu.swu.pulltorefreshswipemenulistview.library.pulltorefresh.interfaces.IXListViewListener;
import edu.swu.pulltorefreshswipemenulistview.library.swipemenu.bean.SwipeMenu;
import edu.swu.pulltorefreshswipemenulistview.library.swipemenu.bean.SwipeMenuItem;
import edu.swu.pulltorefreshswipemenulistview.library.swipemenu.interfaces.OnMenuItemClickListener;
import edu.swu.pulltorefreshswipemenulistview.library.swipemenu.interfaces.OnSwipeListener;
import edu.swu.pulltorefreshswipemenulistview.library.swipemenu.interfaces.SwipeMenuCreator;
import edu.swu.pulltorefreshswipemenulistview.library.util.RefreshTime;



public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener,IXListViewListener {



//    public static Context context ;

    //网络连接模式选择
    public  final static int MODE_UNKNOW_TYPE=-1;
    public final static int MODE_TCP_SERVER=0;
    public final static int MODE_TCP_CLIENT=1;
    public final static int MODE_UDP_Server=2;
    public final static int MODE_UDP_Cleint=3;
    public  final static int MODE_Bluetooth=4;
    public  final static  int MODE_UDP_TYPE = 5;

    private static int comm_mode= 0;
    private static int ser_port = 0;
    private  static  String local_ip="0.0.0.0";
    private static boolean comm_islink = false;

    //TCP服务器通信模式下
    private TCP_service tcp_service =null;

    // TCP客户端通信模式下
    private TCP_client tcp_client =null;

    //UDPf服务器通信模式下
    private  UdpServer udpServer = null;
    private MyBroadcastReceiver myBroadcastReceiver = null;

    //UDP客户端
    private UdpClient udpClient = null;

    private  UdpHelper udphelper = null;

    private WifiManager wifiManager = null;

    public final static int  SERVER_STATE_CORRECT_READ=3;
    public final static int  SERVER_STATE_CORRECT_WRITE=4;               //正常通信信息
    public final static int  SERVER_STATE_ERROR=5;                        //发生错误异常信息
    public final  static int  SERVER_STATE_IOFO=6;                        //发送SOCKET信息

    public final static int  CLIENT_STATE_CORRECT_READ=7;
    public final static int  CLIENT_STATE_CORRECT_WRITE=8;              //正常通信信息
    public final static int  CLIENT_STATE_ERROR=9;                       //发生错误异常信息
    public final static int  CLIENT_STATE_IOFO=10;                       //发送SOCKET信息

    public  static  int sleep_time = 10;
    //复选状态信息
    private  static boolean  Hex_show =false;
    private static boolean  Auto_huang =false;
    private static boolean  Hex_send =false;
    private static boolean  Auto_send =false;

    private static final String TAG = "MainActivity";
    private  static   boolean is_start_acty =false;

    //文本显示控件

    private TextView link_state;                     //设置状态
    private TextView ip_show;                        //连接的对象IP 显示
    private TextView name_show;                      //连接的对象主机名号 显示
    private TextView re_count;                       //接收字节数
    private TextView se_count;                       //发送字节数
    private TextView re_data_show;                   //接收字节显示
    private  TextView btn_changeStatus;

    private  List<String> sendstr_List= null;

    private Button btn_send;
    private  EditText txt_send;

    private  CreateItemDialog itemDialog = null;
//侧滑listview的实现
  //  private List<ApplicationInfo> mAppList;
  //  private AppAdapter mAdapter;
    private  StringAdapter mAdapter;
    private PullToRefreshSwipeMenuListView mListView;
    private Handler mHandler;
    private UdpHandler udpHandler;
    private Thread tReceived = null;



    //计数用
    private int  countin =0;
    private  int countout=0;

    private  boolean fab_opened  = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        comm_init();
        SendDataInit();
        listViewInit();
        wifiManagerInit();
        UdpServerInit();

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        sendFloatViewInit();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);


        Log.d(TAG, "onCreate: test");
    }



    private  boolean sendFloatViewInit()
    {

        try {
            final com.github.clans.fab.FloatingActionMenu fab =(com.github.clans.fab.FloatingActionMenu)findViewById(R.id.fab_send);
            fab.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(!fab_opened)
                    {
                        openFabMenu(view);
                    }else
                    {
                        closeFabMenu(view);
                    }
                }
            });

            com.github.clans.fab.FloatingActionButton fab_add =(com.github.clans.fab.FloatingActionButton)findViewById(R.id.fab_share);
            fab_add.setOnClickListener( new View.OnClickListener()
            {

                @Override
                public void onClick(View v) {
                  Toast.makeText(MainActivity.this,"测试",Toast.LENGTH_SHORT).show();
                    TakeSendPopWin tsp =new TakeSendPopWin( MainActivity.this , sendButtonListener);
                    tsp.showAtLocation(findViewById(R.id.drawer_layout), Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
                    WindowManager.LayoutParams params = getWindow().getAttributes();
                    //当弹出Popupwindow时，背景变半透明
                    params.alpha=0.7f;
                    getWindow().setAttributes(params);
                    //设置Popupwindow关闭监听，当Popupwi
                    tsp.setOnDismissListener( new  TakeSendPopWin.OnDismissListener()
                    {
                        public void onDismiss() {
                            WindowManager.LayoutParams params = getWindow().getAttributes();
                            params.alpha=1f;
                            getWindow().setAttributes(params);
                        }
                    });
                }
            });


            return true;
        }catch (Exception ex)
        {
            Toast.makeText(MainActivity.this,"发生异常，异常原因："+ex.toString() ,Toast.LENGTH_SHORT).show();
            return  false;
        }
    }
    private View.OnClickListener sendButtonListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {

        }
    };

    private void openFabMenu(View view)
    {
        ObjectAnimator animator = ObjectAnimator.ofFloat(view ,"rotation",0,-155,-135);
        animator.setDuration(500);
        animator.start();
//        AlphaAnimation alph = new AlphaAnimation(0.07f,0);
//        alph.setDuration(500);
//        alph.setFillAfter(true);
        fab_opened = true;
    }
    private  void closeFabMenu(View view)
    {
        ObjectAnimator animator = ObjectAnimator.ofFloat(view ,"rotation",-135,20,0);
        animator.setDuration(500);
        animator.start();
//        AlphaAnimation alph = new AlphaAnimation(0.07f,0);
//        alph.setDuration(500);
//        alph.setFillAfter(true);
        fab_opened = false;
    }

    private  boolean  wifiManagerInit()
    {
        if(wifiManager  == null) {
           wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
       //     wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
        }

        //判断wifi是否开启
        if ( (!wifiManager.isWifiEnabled()) || ( wifiManager.getWifiState() != WifiManager.WIFI_STATE_ENABLED ) ) {
            //wifiManager.setWifiEnabled(true);
            return false;
        }else
        {
            return  true;
        }
    }
    public  void SendDataInit()
    {
        sendstr_List = new ArrayList<>(); //Arrays.asList(new String[]{"ace", "boom", "crew", "dog", "eon"}) ;
        sendstr_List.add("01 02 03");
		sendstr_List.add("01");
    }

    public  void listViewInit()
    {

        mListView = (PullToRefreshSwipeMenuListView) findViewById(R.id.send_listView);
        mAdapter = new StringAdapter(MainActivity.this,sendstr_List);
        mListView.setAdapter(mAdapter);
        mListView.setPullRefreshEnable(false);
        mListView.setPullLoadEnable(false);
      //  mListView.setShowHeadIcon(false);
        mListView.setXListViewListener(this);
        mHandler = new Handler();

        // step 1. create a MenuCreator
        SwipeMenuCreator creator = new SwipeMenuCreator() {

            @Override
            public void create(SwipeMenu menu) {
                // create "open" item
                SwipeMenuItem openItem = new SwipeMenuItem(getApplicationContext());
                // set item background
                openItem.setBackground(new ColorDrawable(Color.rgb(0xC9, 0xC9, 0xCE)));
                // set item width
                openItem.setWidth(dp2px(90));
                // set item title
                openItem.setTitle("修改");
                // set item title fontsize
                openItem.setTitleSize(18);
                // set item title font color
                openItem.setTitleColor(Color.WHITE);
                // add to menu
                menu.addMenuItem(openItem);

                // create "delete" item
                SwipeMenuItem deleteItem = new SwipeMenuItem(getApplicationContext());
                // set item background
                deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9, 0x3F, 0x25)));
                // set item width
                deleteItem.setWidth(dp2px(90));
                // set a icon
                deleteItem.setIcon(R.drawable.ic_delete);
                // add to menu
                menu.addMenuItem(deleteItem);
            }
        };
        // set creator
        mListView.setMenuCreator(creator);

        // step 2. listener item click event
        mListView.setOnMenuItemClickListener(new OnMenuItemClickListener() {
            @Override
            public void onMenuItemClick(int position, SwipeMenu menu, int index) {
                String item = sendstr_List.get(position);
                try {
                    switch (index) {
                        case 0:
                            // open
                            //open(item);
                            showEditDialog(position,item , 1);
                            break;
                        case 1:
                            // delete
                            // delete(item);
                            sendstr_List.remove(position);
                            mAdapter.notifyDataSetChanged();
                            break;
                    }
                }catch (Exception ex)
                {
                    Log.e(TAG, "onMenuItemClick error and error is:" + ex.toString() );
                }
            }
        });

        // set SwipeListener
        mListView.setOnSwipeListener(new OnSwipeListener() {

            @Override
            public void onSwipeStart(int position) {
                // swipe start
            }

            @Override
            public void onSwipeEnd(int position) {
                // swipe end
            }
        });

        // other setting
        // listView.setCloseInterpolator(new BounceInterpolator());

        // test item long click
        mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(getApplicationContext(), position + " long click", Toast.LENGTH_SHORT).show();
                return false;
            }
        });

       mListView.setOnItemClickListener( new AdapterView.OnItemClickListener(){

           @Override
           public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
             try {
                 if(position> 0)
                 {
                     position = position -1;
                 }
                 String send_str = sendstr_List.get(position);
                 if (comm_islink) {
                     sendmessage(send_str);
                 } else {
                     Toast.makeText(MainActivity.this, "没有建立通信链接，数据发送失败！", Toast.LENGTH_LONG).show();
                 }
             }catch (Exception ex)
             {
                 Toast.makeText(MainActivity.this,"数据发送异常："+ex.toString(),Toast.LENGTH_SHORT).show();
             }
           }
       } );

    }

    private class UdpHandler extends Handler{
        private final WeakReference<MainActivity> mActivity;
        public UdpHandler(MainActivity activity) {
            mActivity = new WeakReference<MainActivity>(activity);
        }
        @Override
        public void handleMessage(Message msg) {
            MainActivity activity = mActivity.get();
            if (null != activity){
                switch (msg.what){
                    case 1:
                        byte[] str = (byte[])msg.obj;
                        Handler_receive( msg);
                        Log.i(TAG, "handleMessage recv msg is:" + str);
                        break;
                    case 2:
                        String stra = msg.obj.toString();
                        Log.i(TAG, "handleMessage send msg is:" + stra);
                        break;
                    case 3:
                        break;
                }
            }
        }
    }


public  void startUDPService()
{

    udphelper = new UdpHelper(wifiManager , ser_port);
    //传递WifiManager对象，以便在UDPHelper类里面使用MulticastLock
    //udphelper.addObserver(MainActivity.this);
    tReceived = new Thread(udphelper);
    tReceived.start();

}

    public void showEditDialog(int nbr ,String str ,int type)
    {
        itemDialog = new CreateItemDialog(this, R.style.AppTheme, itemChangeListener , nbr , str);
        itemDialog.show();
    }

    private View.OnClickListener itemChangeListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        try {
            switch (v.getId()) {
                case R.id.btn_save_pop:
                    String info = itemDialog.text_info.getText().toString().trim();
                        sendstr_List.remove(itemDialog.item_nbr);
                        sendstr_List.add(itemDialog.item_nbr, info);
                    itemDialog.dismiss();
                    itemDialog = null;
                    mAdapter.notifyDataSetChanged();
                   // itemDialog.Close();
                    break;
                default:
                    itemDialog.dismiss();
                    itemDialog = null;
                    break;
            }
        }catch (Exception ex)
        {
            Log.e(TAG, "修改发送标题内容失败，错误码： "+ ex.toString() );
        }
        }
    };

    private void open(String item) {
        // open app
       Toast.makeText(MainActivity.this,item,Toast.LENGTH_SHORT).show();
    }

    public void onLoadMore() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                onLoad();
            }
        }, 2000);
    }

public  void comm_init()
{
    link_state= (TextView) findViewById(R.id.link_state);
    ip_show= (TextView) findViewById(R.id.ip_adder);
    name_show= (TextView) findViewById(R.id.name_show);
    re_count= (TextView) findViewById(R.id.receive_count);
    se_count= (TextView) findViewById(R.id.send_count);
    re_data_show= (TextView) findViewById(R.id.receive);
  //  edit_data = (TextView) findViewById(R.id.send_data);
    re_data_show.setMovementMethod(ScrollingMovementMethod.getInstance());// 使TextView接收区可以滚动


    txt_send=(EditText) findViewById(R.id.send_txt);

//    btn_send =(Button) findViewById(R.id.send_button);
//    btn_send.setOnClickListener(sendListener);
    btn_changeStatus = (TextView)findViewById(R.id.statusChange);
    btn_changeStatus.setOnClickListener(changeLinkStatusListener);
    btn_changeStatus.setText("开启连接");
    btn_changeStatus.setEnabled(false);

    is_start_acty =true;
    comm_islink =false;
    countin = 0;
    countout = 0;
}

    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
    }

    public void onRefresh() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                SimpleDateFormat df = new SimpleDateFormat("MM-dd HH:mm", Locale.getDefault());
                RefreshTime.setRefreshTime(getApplicationContext(), df.format(new Date()));
                onLoad();
            }
        }, 2000);
    }

    private void onLoad() {
        mListView.setRefreshTime(RefreshTime.getRefreshTime(getApplicationContext()));
        mListView.stopRefresh();

        mListView.stopLoadMore();

    }

    private  boolean closeNetLink()
    {
        boolean rtval =false;
        if(comm_islink)
        {
            try {
                switch (comm_mode) {
                    case MODE_TCP_SERVER:
                        tcp_service.close();

                        rtval = true;
                        break;
                    case MODE_TCP_CLIENT:
                        tcp_client.close();
                        rtval = true;
                        break;
                    case MODE_UDP_Server:
                      rtval =  closeUdpServer();

                        break;
                    case MODE_UDP_Cleint:
                      rtval =  closeUdpClient();

                        break;
                    case MODE_Bluetooth:
                        rtval = true;
                        break;
                }
                comm_islink = false;
                btn_changeStatus.setText("开启连接");
                rtval = true;
            }catch (Exception ex)
            {
                rtval = false;
                Toast.makeText(MainActivity.this,"连接异常！"+ ex.toString(), Toast.LENGTH_SHORT).show();
            }
        }else
        {
            rtval =true;
        }
        return  rtval;
    }

    private View.OnClickListener changeLinkStatusListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                if (((local_ip == "0.0.0.0") || (ser_port == 0) && (!comm_islink))) {
                    Toast.makeText(MainActivity.this, "通信连接建立失败，配置没有初始化！", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (comm_islink) {
                    if (closeNetLink()) {
                        Toast.makeText(MainActivity.this, "通信连接关闭成功！", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this, "通信连接关闭失败！", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    if (local_ip == "0.0.0.0") {
                        Toast.makeText(MainActivity.this, "通信连接建立失败，配置没有初始化！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (StartCommServer()) {
                        Toast.makeText(MainActivity.this, "通信连接建立成功！", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this, "通信连接建立失败！", Toast.LENGTH_SHORT).show();
                    }
                }
            } catch (Exception ex) {
                Toast.makeText(MainActivity.this, "关闭失败，失败原因：" + ex.toString(), Toast.LENGTH_SHORT).show();
            }
        };
    };

    private View.OnClickListener sendListener = new View.OnClickListener() {
        @Override
        public void onClick(View v)
        {
            String send_str = txt_send.getText().toString().replaceAll(" ","");
            if((send_str == null) || (send_str.length() < 1))
            {
                Toast.makeText(MainActivity.this,"发送内容不能为空",
                        Toast.LENGTH_SHORT).show();
            }

         //   Toast.makeText(MainActivity.this,"send hex show:" + String.valueOf(Hex_send) + "recv hex show"+ String.valueOf(Hex_show) + "换行:" + String.valueOf(Auto_huang) ,Toast.LENGTH_SHORT ).show();
            Log.i(TAG, "onClick info is:" + "send hex show:" + String.valueOf(Hex_send) + "recv hex show"+ String.valueOf(Hex_show) + "换行:" + String.valueOf(Auto_huang) );

            sendstr_List.add(send_str);
            mAdapter.notifyDataSetChanged();

            if(comm_islink)
            {
                //edit_data.append(send_str);
                sendmessage(send_str);
            }else
            {
                Toast.makeText(MainActivity.this, "没有建立通信链接，数据发送失败！", Toast.LENGTH_LONG).show();
            }

        }
    };

    protected void onDestroy(){
        if(tcp_service!=null)
        {
            tcp_service.setis_start(false);
            tcp_service.close();
            tcp_service=null;
        }
        if(tcp_client != null){
            tcp_client.close();
            tcp_client=null;
        }
        if(udpClient != null)
        {
            closeUdpClient();
        }
        if(udpServer != null)
        {
            closeUdpServer();
        }

        if(myBroadcastReceiver != null)
        {
            unregisterReceiver(myBroadcastReceiver);
        }

        if(mHandler != null)
        {
            mHandler.removeCallbacksAndMessages(null);
        }
        if (udpHandler !=null)
        {
            udpHandler.removeCallbacksAndMessages(null);
        }
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    public boolean isIP(String addr)
    {
        if(addr.length() < 7 || addr.length() > 15 || "".equals(addr))
        {
            return false;
        }
        /**
         * 判断IP格式和范围
         */
        String rexp = "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}";

        Pattern pat = Pattern.compile(rexp);

        Matcher mat = pat.matcher(addr);

        boolean ipAddress = mat.find();

        return ipAddress;
    }

    // 接收数据处理分析函数，通过handler从子线程回传到主线程
    private  void Handler_receive(Message msg){
        try {
            byte[] buffer = (byte[]) msg.obj;
            if (Hex_show == true) {
                String readMessage = " " + Data_sync.bytesToHexStringHaveSpan(buffer, msg.arg1);
                re_data_show.append(readMessage);
                if (Auto_huang == true) {
                    re_data_show.append("\n");
                }
                countin += readMessage.length() / 2;                               // 接收计数
                re_count.setText("" + countin + "个");
            } else if (Hex_show == false) {
                String readMessage = null;
                try {
                    readMessage = new String(buffer, 0, msg.arg1, "GBK");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                re_data_show.append(readMessage);
                if (Auto_huang == true) {
                    re_data_show.append("\n");
                }
                countin += readMessage.length();                                   // 接收计数
                re_count.setText("" + countin + "个");
            }
        }catch (Exception ex) {
            Toast.makeText(MainActivity.this,"数据接收处理发生错误,错误原因："+ex.toString(),Toast.LENGTH_SHORT).show();
        }
    }
    //定时返回函数
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
           // String message = edit_data.getText().toString();
           // sendmessage(message);
        }
    };





    //发送数据函数
    public void  sendmessage(final String message){

        if(message == null || message.length() < 1)
        {
            Toast.makeText(MainActivity.this,"发送失败，发送数据内容不能为空！" , Toast.LENGTH_SHORT).show();
            return;
        }

        countout += message.length();
        se_count.setText(String.valueOf(countout));

        if(Hex_send == true){
            final byte[] send = Data_sync.hexStr2Bytes(message.replaceAll("\\s*", ""));
            switch (comm_mode)
            {
                case MODE_TCP_SERVER:
                    tcp_service.write(send);
                    break;
                case MODE_TCP_CLIENT:
                    tcp_client.sendmessage(send);
                    break;
                case MODE_UDP_Server:
                    Thread thread1 = new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                           //     final String msg = message;
                                udpServer.Send( send);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                    thread1.start();
                    break;
                case MODE_UDP_Cleint:
                    Thread thread = new Thread(new Runnable() {
                        @Override
                        public void run() {
                                udpClient.send(send);
                            }

                        }
                    );
                    thread.start();

                    break;
                case MODE_Bluetooth:
                    break;
            }

        }else{
           final byte[] send = message.getBytes();
            switch (comm_mode)
            {
                case MODE_TCP_SERVER:
                    tcp_service.write(send);
                    break;
                case MODE_TCP_CLIENT:
                    tcp_client.sendmessage(send);
                    break;
                case MODE_UDP_Server:
                    Thread thread1 = new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                //     final String msg = message;
                                udpServer.Send(send);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                    thread1.start();
                    break;
                case MODE_UDP_Cleint:
                    Thread thread = new Thread(new Runnable() {
                        @Override
                        public void run() {
                            udpClient.send(send);
                        }

                    }
                    );
                    thread.start();
                    break;
                case MODE_UDP_TYPE:
                    udphelper.send(send);
                    break;
                case MODE_Bluetooth:
                    break;
            }

        }
    }

    //发送数据处理分析函数，通过handler从子线程回传主线程
    private void Handler_send(Message msg){
        byte[] writeBuf = (byte[]) msg.obj;
        if (Auto_send == true) {
            String s = String.valueOf(sleep_time);
            long t = Long.parseLong(s);
            ser_handler.postDelayed(runnable, t);
        } else if (Auto_send == false) {
            ser_handler.removeCallbacks(runnable);
        }

        if (Hex_send == true) {
            String writeMessage = Data_sync.Bytes2HexString(writeBuf);
            countout += writeMessage.length() / 2;
            se_count.setText("" + countout+"个");
        } else if (Hex_send == false) {
            String writeMessage = null;
            try {
                writeMessage = new String(writeBuf, "GBK");
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }
            countout += writeMessage.length();
            se_count.setText("" + countout+"个");
        }
    }


    private Handler ser_handler =new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what==SERVER_STATE_ERROR){
                Toast.makeText(MainActivity.this,"连接异常"
                        , Toast.LENGTH_SHORT).show();
                link_state.setText("TCP服务器模式 连接异常");
                ip_show.setHint("对象IP");
                name_show.setHint("对象主机名");
                comm_islink=false;
                link_state.setText("TCP服务 连接异常");
                btn_changeStatus.setText("重新连接");
                btn_changeStatus.setEnabled(false);
            }
            //发送数据
            if (msg.what==SERVER_STATE_CORRECT_WRITE){
                Handler_send(msg);
            }
            //接收数据
            if(msg.what==SERVER_STATE_CORRECT_READ){
                Handler_receive(msg);
            }
            if(msg.what==SERVER_STATE_IOFO){
                comm_islink=true;
                link_state.setText("TCP服务器模式(端口"+se_count+")  建立连接 ");
                ip_show.setHint("对象IP:"+local_ip);
//                try {
//                    NbtAddress nbtAddress = NbtAddress.getByName(local_ip);
//                    name_show.setText("对象主机名："+nbtAddress.getHostName());
//                }catch (UnknownHostException ex)
//                {
//                    name_show.setHint("对象主机名");
//                }
                btn_changeStatus.setText("关闭TCP服务器");
                btn_changeStatus.setEnabled(true);
                String[] strings= (String[]) msg.obj;
                ip_show.append(strings[0]+"\n");
                name_show.append(strings[1]+"\n");
            }
        }
    };
    //客户端通信模式下
    private  Handler cli_handler =new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch( msg.what){
                case CLIENT_STATE_ERROR :
                    Toast.makeText(MainActivity.this,"连接异常"
                            ,Toast.LENGTH_SHORT).show();
                    link_state.setText("TCP客户端模式 连接异常");
                    ip_show.setHint("对象IP");
                    name_show.setHint("对象主机名");
                    comm_islink=false;
                    btn_changeStatus.setText("重新连接");
                    btn_changeStatus.setEnabled(false);
                    break;
                case CLIENT_STATE_IOFO :
                    comm_islink  =true;
                    link_state.setText("TCP客户端模式(端口"+ser_port+")  建立连接");
//                    try {
//                        NbtAddress nbtAddress = NbtAddress.getByName(local_ip);
//                        name_show.setText("对象主机名："+nbtAddress.getHostName());
//                    }catch (UnknownHostException ex)
//                    {
//                        name_show.setHint("对象主机名");
//                    }
                    btn_changeStatus.setText("关闭连接");
                    btn_changeStatus.setEnabled(true);
                    String[] strings= (String[]) msg.obj;
                    ip_show.append(strings[0]+"\n");
                    name_show.append(strings[1]+"\n");
                    break;
                //接收数据
                case CLIENT_STATE_CORRECT_READ :
                    Handler_receive(msg);
                    break;
                //发送数据
                case CLIENT_STATE_CORRECT_WRITE:
                    Handler_send(msg);
                    break;
            }
        }
    };

    private  boolean  UdpServerInit()
    {
        myBroadcastReceiver = new MyBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter("udpReceiver");
        registerReceiver(myBroadcastReceiver,intentFilter);

        return true;
    }

    private  boolean isWifi(Context mContext) {
        ConnectivityManager connectivityManager = (ConnectivityManager) mContext
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetInfo != null
                && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            return true;
        }
        return false;
    }

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.hasExtra("udpReceiver"))  {
                Message message = new Message();
                message.obj = intent.getByteArrayExtra("udpReceiver");
                int recvlen = intent.getIntExtra("recv_len" ,0);
                message.what = 1;
                message.arg1 = recvlen;
                Log.i("主界面Broadcast","收到"+message.obj.toString());
                udpHandler.sendMessage(message);
            }
        }
    };

    private class MyBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String mAction = intent.getAction();
            switch (mAction){
                case "udpReceiver":
                    byte recv[] =intent.getByteArrayExtra("udpReceiver");
                    int recvlen = intent.getIntExtra("recv_len" ,0);
                    Message message = new Message();
                    message.what = 1;
                    message.obj = recv;
                    message.arg1 = recvlen;
                    udpHandler.sendMessage(message);
                    break;
            }
        }
    }

    private  boolean startUdpServer()
    {

        boolean rtval = false;
        udpHandler = new UdpHandler(this);
        try {
            ExecutorService exec = Executors.newCachedThreadPool();
            udpServer = new UdpServer(local_ip, ser_port ,MainActivity.this );
            exec.execute(udpServer);
            udpHandler = new UdpHandler(this);
            rtval =true;

            //udpServer = new UdpServer(local_ip, ser_port , MainActivity.this);
           // Thread thread = new Thread(udpServer);
            //thread.start();
            rtval =true;
        }catch (Exception ex)
        {
            rtval =false;
           // link_state.setText("UDP服务器端模式(端口+"+ser_port+")  启动失败");
            Toast.makeText(MainActivity.this,"建立UDP服务异常："+ ex.toString(),Toast.LENGTH_SHORT).show();
        }
        return  rtval;
    }

    public  Boolean closeUdpServer()
    {
        Boolean rtval =false;
        try {
            /*
            final Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    //关闭UDP
                    udpServer.setUdpLife(false);
                    while (udpServer.getLifeMsg()) ; //等待udp阻塞结束，这里就体现出超时的好处了
                    Looper.getMainLooper();
                }
            });
            thread.start();
            udpServer = null;
            udpHandler = null;
            */
            udpServer.setUdpLife(false);
            udpServer = null;
            if (udpHandler !=null)
            {
                udpHandler.removeCallbacksAndMessages(null);
            }
            udpHandler = null;
            rtval =true;
        }catch (Exception ex)
        {
            rtval =false;
            Toast.makeText(MainActivity.this,"关闭UDP服务异常："+ ex.toString(),Toast.LENGTH_SHORT).show();
        }
        return  rtval;
    }

    private  Boolean startUdpClient()
    {
        Boolean rtval =false;
        try {

            ExecutorService exec = Executors.newCachedThreadPool();
            udpClient = new UdpClient(local_ip, ser_port ,MainActivity.this );
            exec.execute(udpClient);
            udpHandler = new UdpHandler(this);
            rtval =true;
        }catch (Exception ex)
        {
            rtval =false;
            Toast.makeText(MainActivity.this,"打开UDP客户端异常："+ ex.toString(),Toast.LENGTH_SHORT).show();
           // link_state.setText("UDP客户端模式(端口+"+ser_port+")  启动异常");
        }
        return  rtval;
    }

    private  Boolean closeUdpClient()
    {
        Boolean rtval =false;
        try {
            udpClient.setUdpLife(false);
            udpClient = null;
            if (udpHandler !=null)
            {
                udpHandler.removeCallbacksAndMessages(null);
            }
            udpHandler = null;
            rtval =true;
        }catch (Exception ex)
        {
            rtval =false;
            Toast.makeText(MainActivity.this,"关闭UDP客户端异常："+ ex.toString(),Toast.LENGTH_SHORT).show();
        }
        return  rtval;
    }

        private   boolean StartCommServer()
    {
        try {
            if (!is_start_acty) {
                Log.d(TAG, "StartCommServer: MainActivity is null ! ");
            }

            changeCommType(comm_mode, local_ip, ser_port);
            switch (comm_mode) {
                case MODE_TCP_SERVER:
                    if ((tcp_service == null) || (!comm_islink)) {
                        if(tcp_service != null)
                        {
                            tcp_service = null;
                        }
                        tcp_service = new TCP_service(ser_handler, ser_port);
                        tcp_service.start();
                        comm_islink = true;
                        link_state.setText("TCP服务器模式(端口"+ser_port+")  启动");
                        ip_show.setHint("本机IP:"+ local_ip);
                        btn_changeStatus.setText("关闭TCP服务器");
                        btn_changeStatus.setEnabled(true);

                    } else {
                        ip_show.setHint("本机IP:"+ local_ip);
                        Log.e(TAG, "断开连接监听 释放资源");
                        comm_islink = false;
                        link_state.setText("TCP服务器模式  出错");
                        btn_changeStatus.setEnabled(false);
                    }
                    break;
                case MODE_TCP_CLIENT:
                    {
                    if ((tcp_client == null) || (!comm_islink)) {
                        if(tcp_client != null)
                        {
                            tcp_client = null;
                        }
                        tcp_client = new TCP_client(cli_handler);
                        try {
                            InetAddress ipAddress = InetAddress.getByName
                                    (local_ip);
                            tcp_client.setInetAddress(ipAddress);
                            tcp_client.setPort(ser_port);
                            tcp_client.start();
                            comm_islink = true;
                            link_state.setText("TCP客户端模式(端口"+ser_port+") 启动");
                            ip_show.setText("对象IP：" + local_ip);
                            name_show.setText("对象主机名");
                            btn_changeStatus.setText("关闭TCP客户端");
                            btn_changeStatus.setEnabled(true);
                        } catch (UnknownHostException e) {
                            e.printStackTrace();
                            comm_islink = false;
                            link_state.setText("TCP客户端模式  连接异常");
                            name_show.setText("对象主机名");
                            btn_changeStatus.setEnabled(false);
                        }

                    }
                }
                    break;
                case MODE_UDP_Server:
                    if( udpServer != null)
                    {
                        closeUdpServer();
                    }
                    if(startUdpServer())
                    {
                        link_state.setText("UDP服务器模式(端口"+ser_port+")  启动");
                        ip_show.setText("本地IP：" + local_ip);
                        name_show.setText("对象主机名");
                        comm_islink  =true;
                        btn_changeStatus.setText("关闭UDP服务器");
                        btn_changeStatus.setEnabled(true);
                    }else
                    {
                        link_state.setText("UDP服务器模式(端口"+ser_port+")  启动失败");
                        ip_show.setText("本地IP：" + local_ip);
                        name_show.setText("对象主机名");
                        comm_islink =false;
                        btn_changeStatus.setEnabled(false);
                    }
                    break;
                case MODE_UDP_Cleint:
                    if(udpClient != null )
                    {
                        closeUdpClient();
                    }
                    if(startUdpClient())
                    {
                        link_state.setText("UDP客户端模式(端口+"+ser_port+")  启动");
                        ip_show.setText("对象IP：" + local_ip);
                        name_show.setText("对象主机名");
                        comm_islink  = true;
                        btn_changeStatus.setText("关闭UDP客户端");
                        btn_changeStatus.setEnabled(true);
                    }else
                    {
                        link_state.setText("UDP客户端模式(端口+"+ser_port+")  启动失败");
                        ip_show.setText("对象IP：" + local_ip);
                        comm_islink = false;
                        btn_changeStatus.setEnabled(false);
                    }
                    break;
                case MODE_Bluetooth:
                    comm_islink = false;
                    Toast.makeText(MainActivity.this,"暂不支持蓝牙模式" , Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;


            }
        }catch (Exception ex)
        {
            Log.e(TAG, "StartCommServer err ,msg is "+ ex.toString() );
        }

        return  false;
    }

    public  boolean changeCommType(int type,String ip,int port)
    {

        switch (type)
        {
            case MODE_TCP_SERVER:
                comm_mode = type;
                if( (String.valueOf(port) ==  null) || (port < 0) || (port>65535)) {
                    Toast.makeText(MainActivity.this,"端口设置错误",
                            Toast.LENGTH_SHORT).show();
                    return false;
                }
                ser_port = port;
                break;
            case MODE_TCP_CLIENT:
                comm_mode =type;
                if( (String.valueOf(port) == null) || (port < 0) || (port>65535)) {
                    Toast.makeText(MainActivity.this,"端口设置错误",
                            Toast.LENGTH_SHORT).show();
                    return false;
                }
                ser_port= port;
                if((ip == null) || (!isIP(ip) ))
                {
                    Toast.makeText(MainActivity.this,"IP设置错误",
                            Toast.LENGTH_SHORT).show();
                    return  false;
                }
                local_ip = ip;
                break;
            case MODE_UDP_Server:
                comm_mode = type;
                if( (String.valueOf(port) == null) || (port < 0) || (port>65535)) {
                    Toast.makeText(MainActivity.this,"端口设置错误",
                            Toast.LENGTH_SHORT).show();
                    return false;
                }
                ser_port = port;
              break;
            case MODE_UDP_Cleint:
                comm_mode =type;
                if( (String.valueOf(port) == null) || (port < 0) || (port>65535)) {
                    Toast.makeText(MainActivity.this,"端口设置错误",
                            Toast.LENGTH_SHORT).show();
                    return false;
                }
                ser_port= port;
                if((ip == null) || (!isIP(ip) ))
                {
                    Toast.makeText(MainActivity.this,"IP设置错误",
                            Toast.LENGTH_SHORT).show();
                    return  false;
                }
                local_ip = ip;
                break;
            case MODE_UDP_TYPE:
                comm_mode =type;
                if( (String.valueOf(port) == null) || (port < 0) || (port>65535)) {
                    Toast.makeText(MainActivity.this,"端口设置错误",
                            Toast.LENGTH_SHORT).show();
                    return false;
                }
                ser_port= port;
                if((ip == null) || (!isIP(ip) ))
                {
                    Toast.makeText(MainActivity.this,"IP设置错误",
                            Toast.LENGTH_SHORT).show();
                    return  false;
                }
                local_ip = ip;
                break;
            case MODE_Bluetooth:
                return  false;
            default:
                Toast.makeText(MainActivity.this,"未知的通信类型",
                        Toast.LENGTH_SHORT).show();
                return  false;
        }
        return  true;
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            Intent intent =  new Intent();
            Bundle bundle = new Bundle();
            bundle.putInt("comm_mode",comm_mode);
            bundle.putString("ip",local_ip);
            bundle.putInt("port",ser_port);
            intent.putExtras(bundle);
            intent.setClass(MainActivity.this,CommSettingActivity.class);
          //  startActivity(intent);
           startActivityForResult(intent,0);
        }else if(id == R.id.blue_settings)
        {
            try {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, com.xiaoding.activity.BlueUsingActivity.class);
                startActivity(intent);
            }catch (Exception ex)
            {
                Toast.makeText(MainActivity.this,"蓝牙打开异常，原因："+ex.toString(),Toast.LENGTH_SHORT).show();
            }
        }

        return super.onOptionsItemSelected(item);
    }

    //清除函数
    private void clear() {
        countin=0;
        countout=0;
        re_count.setText("0个");
        se_count.setText("0个");
        re_data_show.setText("");
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.i(TAG, "onActivityResult "+" requestCode"+requestCode+"\n resultCode="+resultCode);
        String str = "";
        try {
            if (resultCode == RESULT_OK) {
                clear();
                comm_mode = data.getIntExtra("comm_mode", MODE_TCP_SERVER);
                Log.i(TAG, "通信类型：" + comm_mode);
                Hex_show = data.getBooleanExtra("Hex_show",false);
                Hex_send = data.getBooleanExtra("Hex_send",false);
                Auto_send =data.getBooleanExtra("Auto_send",false);
                Auto_huang =data.getBooleanExtra("Auto_huang",false);
                Log.i(TAG, "onActivityResult: Hex_show is: " + Hex_show + " Hex_send is: "+ Hex_send +" Auto_send is :" +Auto_send + " Auto_huang is: " + Auto_huang);
                switch (comm_mode) {
                    case MODE_TCP_SERVER:
                        str = data.getStringExtra("port");
                        ser_port = Integer.parseInt(str);
                        local_ip = data.getStringExtra("ip");
                        break;
                    case MODE_TCP_CLIENT:
                        str=data.getStringExtra("port");
                        ser_port = Integer.parseInt(str);
                        local_ip = data.getStringExtra("ip");
                        break;
                    case MODE_UDP_Server:
                        str = data.getStringExtra("port");
                        ser_port = Integer.parseInt(str);
                        local_ip = data.getStringExtra("ip");
                        break;
                    case MODE_UDP_Cleint:
                        str = data.getStringExtra("port");
                        ser_port = Integer.parseInt(str);
                        local_ip = data.getStringExtra("ip");
                        break;
                    case MODE_Bluetooth:
                        break;
                    default:
                        Toast.makeText(MainActivity.this,"不支持的通信类型！",Toast.LENGTH_SHORT).show();
                        break;
                }
                StartCommServer();
            }
        }catch (Exception ex)
        {
            Log.e(TAG, "onActivityResult: "+ ex.toString());
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            // Handle the camera action
           // Log.d(TAG, getString(id));
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}
